<script setup>
import { ref, watch, nextTick } from "vue";

// 导入element-plus中的icon组件

import {
    Check,
    Delete,
} from "@element-plus/icons-vue"

import {
    getOrderByStatusService,
    getOrderDetailByOrderIdService,
    getDiscountByPointService,
    createPaymentService,
    getMemberInfoService,
    confirmOrderService,
    modifyOrderService,
    cancelOrderService,
} from '@/src-client/api/operation'

import { ElMessage } from 'element-plus';
import router from "@/src-client/router";



const orderStatus = ref(2)






const total = ref(1)

const orders = ref([
    {
        orderId: null,
        userId: null,
        orderDateTime: '',
        updateDateTime: '',
        status: null,
        totalPrice: null,
        discountAmount: null,
        actualAmountDue: null,
        discountPoint: null,
        earnedPoints: null,
        paymentMethod: null
    }
    // 可以添加更多的订单对象
]);

const orderDetails = ref(
    {
        orderId: 1,
        orderDateTime: null,
        updateDateTime: null,
        status: null,
        totalPrice: null,
        discountAmount: null,
        actualAmountDue: null,
        paymentMethod: null,
        userName: '',
        email: '',
        phoneNumber: '',
        ticketVOS: ref([
            {
                ticketId: null,
                scheduleId: null,
                seatId: null,
                flightId: null,
                classId: null,
                className: '',
                description: '',
                rowNumber: '',
                columnNumber: '',
                seatNumber: '',
                status: null,
                price: null,
                seatType: '',
                facilities: '',
                createTime: null,
                updateTime: null,
                purchaseDate: null,
                departureDate: null,
                departureTime: null,
                arrivalDate: null,
                arrivalTime: null,
                delayInfo: null,
                departureAirportName: '',
                arrivalAirportName: '',
                flightDistance: null,
                flightNumber: ''
            }
            // 可以根据需要添加更多的票详情对象
        ])
    }
    // 可以根据需要添加更多的订单对象
);


const getOrderByStatus = async () => {

    let params = new URLSearchParams();
    params.append('status', orderStatus.value);

    let result = await getOrderByStatusService(params);

    console.log(result);
    if (result.code === 200) {
        orders.value = result.data;
        console.log(orders.value);
    } else {
        ElMessage.error(result.msg);
    }

}



const tokenStore = useTokenStore();

if (tokenStore.token) {
    getOrderByStatus();
}



// 获取订单详情
const getOrderDetailByOrderId = async (orderId) => {

    let result = await getOrderDetailByOrderIdService(orderId);

    console.log(result);
    if (result.code === 200) {

        orderDetails.value = result.data;
    } else {
        ElMessage.error(result.msg);
    }

}

const dialogOfOrderDetailVisible = ref(false);


const orderDetail = (orderId) => {

    getOrderDetailByOrderId(orderId);
    dialogOfOrderDetailVisible.value = true;

}




const formatOrderStatus = (status) => {

    if (status === 2) {
        return "订单已经生成"
    } else if (status === 3) {
        return "订单已确认"
    } else if (status === 5) {
        return "订单已支付"
    } else if (status === 8) {
        return "订单已完成"
    } else {
        return "未知状态"

    }

}



const formatTicketStatus = (status) => {
    const statusMap = {
        1: '可购票',
        2: '待支付',
        3: '已完成',
        5: '已支付'

    };
    return statusMap[status] || '未知状态';
};


const isVisibleOfConfirmDrawer = ref(false);

const handConfirmOrder = async (orderId) => {

    isVisibleOfConfirmDrawer.value = true;

    getOrderDetailByOrderId(orderId);
    getDiscountByPoint(orderId);

}



const discountType = ref({

    discountTypeId: 1,
    typeName: '无可用折扣'

});

const getDiscountByPoint = async (orderId) => {

    let result = await getDiscountByPointService(orderId);

    if (result.code === 200) {
        console.log(result.data);
        discountType.value = result.data;

    }
}

const registerMember = () => {
    router.push('/user/member');
}


const totalPoints = ref(0);

const isMember = ref(false);
const getMemberInfo = async () => {

    let result = await getMemberInfoService();

    if (result.code === 200) {


        isMember.value = true;
        totalPoints.value = result.data.totalPoints;
    }
}


// 监视 isVisibleOfConfirmDrawer 的变化
watch(isVisibleOfConfirmDrawer, (newValue) => {
    if (newValue) {
        // 当抽屉打开时调用 getMemberInfo
        getMemberInfo();
    }
});



const createPayment = async () => {

    let result = await createPaymentService(orderDetails.value.orderId);

    if (result.code === 200) {

        ElMessage.success(result.msg);
    }

    // 刷新订单列表
    isVisibleOfPayDrawer.value = false;

    orderStatus.value = 5;
    getOrderByStatus();

}

// 折扣额度模型
const mortgagePoint = ref(0);


// 确认订单
const confirmOrder = async () => {


    let params = new URLSearchParams();
    params.append('orderId', orderDetails.value.orderId);
    params.append('mortgagePoint', mortgagePoint.value);
    params.append('discountTypeId', discountType.value.discountTypeId);

    let result = await confirmOrderService(params);

    if (result.code === 200) {

        ElMessage.success(result.msg);
        isVisibleOfConfirmDrawer.value = false;
    }

    // 刷新订单列表
    orderStatus.value = 3;
    getOrderByStatus();

}

// 支付弹窗控制
const isVisibleOfPayDrawer = ref(false);

const handelPay = async (orderId) => {

    isVisibleOfPayDrawer.value = true;
    getOrderDetailByOrderId(orderId);
}



// 改签数据模型

import {

    useChangeTicketStore,

} from "@/src-client/stores/changeTicket.js"

import {

    useoldTicketStore,

} from "@/src-client/stores/oldTicket.js"

import {

    useOrderStore,

} from "@/src-client/stores/order.js"

import {
    useChangDialogStatusStore
} from "@/src-client/stores/changeDialogStatus.js"
import { useTokenStore } from "@/src-client/stores/token";



const changeTicketStore = useChangeTicketStore();
const oldTicketStore = useoldTicketStore();
const orderStore = useOrderStore();
const changeDialogStatusStore = useChangDialogStatusStore();


const modiyOrder = async () => {
    // 和后端进行数据交互
    let params = new URLSearchParams();
    params.append('orderId', orderStore.order.orderId);
    params.append('oldticketId', oldTicketStore.ticket.ticketId);
    params.append('newticketId', changeTicketStore.ticket.ticketId);

    let result = await modifyOrderService(params);


    if (result.code === 200) {

        ElMessage.success(result.msg);
        // 刷新订单列表

        changeDialogStatusStore.removeChangDialogStatus();
        changeTicketStore.removeTicket();
        oldTicketStore.removeTicket();
        isVisibleOfChangeDialog.value = false;

        getOrderByStatus();
    } else {
        ElMessage.error(result.msg);
    }

    // 关闭改签弹窗




}



const isVisibleOfChangeDialog = ref(false);


if (changeDialogStatusStore.ChangDialogStatus === 1) {
    isVisibleOfChangeDialog.value = true;
}

const handleChange = async (order) => {



    getOrderDetailByOrderId(order.orderId);


    //  打开订单详情弹窗,选择需要改签的票,一次只能选择一个票进行改签
    isVisibleOfChangeDialog.value = true;

    orderStore.setOrder(order);


}


const handleCancel = async (orderId) => {



}



const handleSelectionTicket = async (row) => {



    oldTicketStore.setTicket(row);
    console.log(oldTicketStore.ticket);


    // 关闭订单详情弹窗
    dialogOfOrderDetailVisible.value = false;
}



const handleSelectionNewTicket = async () => {
    // 跳转到票务选择页面
    isVisibleOfChangeDialog.value = false;

    await router.push('/operation/ticket');

    nextTick(() => {
        watch(
            () => changeTicketStore.ticket,
            async (newValue) => {
                if (newValue?.ticketId && newValue?.seatNumber) {

                    // 更新新票务数据
                    await router.push('/operation/order');
                }
            }
        );
    });
};




// 退掉某票据


const handleCancelTicket = async (row) => {

    let orderId = orderDetails.value.orderId;

    let params = new URLSearchParams();
    params.append('orderId', orderId);
    params.append('ticketId', row.ticketId);

    let result = await cancelOrderService(params);

    if (result.code === 200) {

        ElMessage.success(result.msg);
        // 刷新订单列表
        orderDetail(orderId);
    } else {
        ElMessage.error(result.msg);
    }

}







</script>

<template>
    <el-card>

        <template>
            <div class="header">
                <span>订单管理</span>
            </div>
        </template>

        <el-form-item label="订单状态" style="width: 200px;">
            <el-select aria-placeholder="请选择订单状态" v-model="orderStatus" @change="getOrderByStatus">
                <el-option label="订单已经生成" value="2"></el-option>
                <el-option label="订单已确认" value="3"></el-option>
                <el-option label="订单已支付" value="5"></el-option>
                <el-option label="订单已完成" value="8"></el-option>
            </el-select>
        </el-form-item>


        <el-table :data="orders" style="width: 100%">
            <el-table-column prop="orderId" label="订单号" width="100"></el-table-column>

            <el-table-column prop="status" label="订单状态" width="150">
                <template #default="{ row }">
                    {{ formatOrderStatus(row.status) }}
                </template>
            </el-table-column>

            <el-table-column prop="totalPrice" label="票据总价" width="120"></el-table-column>

            <!-- 显示折扣金额，如果订单状态不是"订单已经创建" -->
            <el-table-column v-if="orderStatus !== 2" prop="discountAmount" label="折扣金额" width="100"></el-table-column>

            <!-- 显示应付金额，如果订单状态不是"订单已经创建" -->
            <el-table-column v-if="orderStatus !== 2" prop="actualAmountDue" label="实际应付" width="100"></el-table-column>

            <!-- 显示积分抵扣额度，如果订单状态不是"订单已经创建" -->
            <el-table-column v-if="orderStatus !== 2" prop="discountPoint" label="积分抵扣" width="100"></el-table-column>

            <!-- 显示已获得积分，订单状态为"订单已支付" -->
            <el-table-column v-if="orderStatus == 5" prop="earnedPoints" label="已获得积分" width="100"></el-table-column>

            <el-table-column prop="orderDateTime" label="订单生成时间" width="180"></el-table-column>

            <el-table-column label="订单详情" width="120">
                <template #default="{ row }">
                    <el-button type="text" @click="orderDetail(row.orderId)">查看详情</el-button>
                </template>
            </el-table-column>




            //确认订单
            <el-table-column v-if="orderStatus == 2" label="去确认订单" width="100">
                <template #default="{ row }">
                    <el-button :icon="Check" circle plain type="primary"
                        @click="handConfirmOrder(row.orderId)"></el-button>
                </template>
            </el-table-column>

            <!-- 支付按钮 -->
            <el-table-column v-if="orderStatus == 3" label="去支付" width="100">
                <template #default="{ row }">
                    <el-button :icon="Check" circle plain type="primary" @click="handelPay(row.orderId)"></el-button>
                </template>
            </el-table-column>

            <!-- 改签按钮 -->

            <el-table-column v-if="orderStatus == 5" label="去改签" width="100">
                <template #default="{ row }">
                    <el-button :icon="Check" circle plain type="primary" @click="handleChange(row)"></el-button>
                </template>
            </el-table-column>

            <el-table-column v-if="orderStatus != 8" label="去退票" width="80">
                <template #default="{ row }">
                    <!-- 取消订单按钮 -->
                    <el-button :icon="Delete" plain type="danger" circle @click="orderDetail(row.orderId)"></el-button>
                </template>
            </el-table-column>

        </el-table>
    </el-card>

    <!-- 确认支付弹窗 -->
    <el-dialog title="确认支付" v-model="isVisibleOfPayDrawer">

        <el-form>
            <el-form-item label="支付确认">
                <button type="button" class="el-button el-button--primary" @click="createPayment()">确认支付</button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!-- 订单详情弹窗 -->
    <el-dialog v-model="dialogOfOrderDetailVisible" title="订单详情" width="100%">



        <el-from>
            <el-row>

                <el-form-item label="用户名" style="width: 200px;">
                    {{ orderDetails.userName }}

                </el-form-item>
                <el-form-item label="邮箱" style="width: 200px;">
                    {{ orderDetails.email }}
                </el-form-item>

                <el-form-item label="手机号" style="width: 200px;">
                    {{ orderDetails.phoneNumber }}
                </el-form-item>
            </el-row>
        </el-from>


        <el-table :data="orderDetails.ticketVOS" style="width: 100%">

            <el-table-column prop="ticketId" label="票据号" width="80"></el-table-column>
            <el-table-column prop="seatNumber" label="座位号" width="120"></el-table-column>
            <el-table-column prop="price" label="票价" width="120"></el-table-column>
            <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                    {{ formatTicketStatus(row.status) }}
                </template>
            </el-table-column>

            <el-table-column prop="flightNumber" label="航班号" width="120"></el-table-column>
            <el-table-column prop="flightDistance" label="航程距离" width="120"></el-table-column>
            <el-table-column prop="departureAirportName" label="出发机场" width="120"></el-table-column>
            <el-table-column prop="arrivalAirportName" label="到达机场" width="120"></el-table-column>
            <el-table-column prop="seatType" label="座位类型" width="120"></el-table-column>
            <!--出发时间  -->
            <el-table-column prop="departureDate" label="出发日期" width="120"></el-table-column>
            <el-table-column prop="departureTime" label="出发时间" width="120"></el-table-column>
            <!--到达时间  -->
            <el-table-column prop="arrivalDate" label="到达日期" width="120"></el-table-column>
            <el-table-column prop="arrivalTime" label="到达时间" width="120"></el-table-column>
            <el-table-column prop="className" label="座位等级" width="120"></el-table-column>
            <el-table-column prop="description" label="描述" width="300"></el-table-column>

            <!-- 选择票据 -->
            <el-table-column label="选择票据">
                <template #default="{ row }">
                    <el-button :icon="Check" circle plain type="primary"
                        @click="handleSelectionTicket(row)"></el-button>
                </template>
            </el-table-column>

            <el-table-column label="退票" width="80">
                <template #default="{ row }">
                    <!-- 取消订单按钮 -->
                    <el-button :icon="Delete" plain type="danger" circle @click="handleCancelTicket(row)"></el-button>
                </template>
            </el-table-column>

        </el-table>

    </el-dialog>

    <!-- 改签弹窗 -->
    <el-dialog title="改签" v-model="isVisibleOfChangeDialog" width="50%">

        <el-form>
            <!-- 渲染订单号 -->
            <el-form-item label="订单号">
                {{ orderStore.order.orderId }}
            </el-form-item>

            <!-- 渲染原票号，并点击后打开订单详情弹窗 -->
            <el-form-item label="原票">
                <div style="display: flex; align-items: center;">
                    <el-button type="text" @click="orderDetail(orderDetails.orderId)" style="margin-right: 10px;">
                        查看订单详情
                    </el-button>
                    <div style="margin-right: 15px;">
                        <strong>票据号：</strong><span>{{ oldTicketStore.ticket.ticketId }}</span>
                    </div>
                    <div>
                        <strong>座位号：</strong><span>{{ oldTicketStore.ticket.seatNumber }}</span>
                    </div>
                </div>
            </el-form-item>

            <!-- 选择新票 -->
            <el-form-item label="新票">
                <div style="display: flex; align-items: center;">
                    <el-button type="text" @click="handleSelectionNewTicket()" style="margin-right: 10px;">
                        查看新票
                    </el-button>
                    <div style="margin-right: 15px;">
                        <strong>票据号：</strong><span>{{ changeTicketStore.ticket.ticketId }}</span>
                    </div>
                    <div>
                        <strong>座位号：</strong><span>{{ changeTicketStore.ticket.seatNumber }}</span>
                    </div>
                </div>
            </el-form-item>





            <el-button type="primary" @click="modiyOrder()">提交改签</el-button>
        </el-form>
    </el-dialog>

    <!-- 订单支付抽屉 -->
    <el-drawer title="订单支付" v-model="isVisibleOfConfirmDrawer" width="50%">

        <el-form>

            <!-- 现有积分 -->
            <el-form-item label="现有积分">
                {{ totalPoints }}
            </el-form-item>

            <el-form-item label="可用折扣类型名称">
                {{ discountType.typeName }}
            </el-form-item>

            <!-- 会员注册 -->
            <el-form-item v-if="isMember === false" label="会员注册">
                <el-button type="primary" @click="registerMember()">会员注册</el-button>
            </el-form-item>

            <!-- 选择抵扣积分额度 -->
            <el-form-item v-if="discountType.discountTypeId !== 1 && discountType.discountTypeId !== 4
                && isMember === true" label="输入抵扣积分额度">
                <input type="number" v-model="mortgagePoint"></input>
            </el-form-item>

            <!-- 确认订单 -->

            <el-form-item label="确认订单">

                <el-button type="primary" @click="confirmOrder()">确认订单</el-button>

            </el-form-item>










        </el-form>





    </el-drawer>



</template>

<style>
/* 可以在这里添加更多的样式 */
</style>